import logging
import os
import time


def get_logger(logger_name,log_dir, prefix="log"):
    # logging INFO
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    log_name = time.asctime().replace(':', "-").replace(" ", "_")
    print(__file__)
    logger = logging.getLogger(logger_name)
    logger.setLevel(level=logging.INFO)
    handler = logging.FileHandler("{}/{}_{}_log.txt".format(log_dir, prefix, log_name), mode='w',
                                  encoding='utf-8')
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    # 2. 添加终端显示的 StreamHandler
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(formatter)
    # 添加到 logger
    logger.addHandler(console_handler)

    return logger

def config_root_logger(log_dir=None, prefix="log"):
    """
    如果没有指定 log_dir 则只输出到终端
    如果指定了 log_dir 则同时输出到文件和终端
    """
    log_name = time.asctime().replace(':', "-").replace(" ", "_")
    # log_format = '%(asctime)s - %(filename)s - %(name)s - %(levelname)s - %(message)s'
    log_format = '%(asctime)s - %(filename)s - %(levelname)s - %(message)s'
    if log_dir is not None:
        handlers = [
            # FileHandler 以 utf-8 编码写入日志文件
            logging.FileHandler("{}/{}_{}_log.txt".format(log_dir, prefix, log_name), mode='w',
                                encoding='utf-8'),
            # StreamHandler 用于将日志输出到终端
            logging.StreamHandler()
        ]
    else:
        handlers = [
            # StreamHandler 用于将日志输出到终端
            logging.StreamHandler()
        ]

    logging.basicConfig(level=logging.INFO,  # 设置日志级别为 INFO
                        format=log_format,  # 设置日志格式
                        handlers=handlers)